package com.situ.stl.interceptor;

import com.situ.stl.constants.Constants;
import com.situ.stl.entity.Admin;
import com.situ.stl.service.AdminService;
import com.situ.stl.util.JWTUtil;
import com.situ.stl.util.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminService adminService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的Token
        String token = request.getHeader(Constants.TOKEN);

        // 获取请求地址
        String uri = request.getRequestURI();

        if (uri.equals("/static/page/index.html") || uri.equals("/static/page/hot.html") ||uri.equals("/static/page/home.html") || uri.equals("/static/page/login.html")|| uri.equals("/static/page/msg.html")||uri.equals("/static/page/my.html")) {
            return true;
        }
        // 当前登录用户
        Admin admin = null;
        // 获取请求token
        if (StringUtils.hasText(token)) {
            // 尝试解析
            try {
                Claims claims = JWTUtil.parseJWT(token);
                String phone = claims.getSubject();
                admin = adminService.getAdminByPhone(phone);
            } catch (Exception e) {
                log.info("无效的token");
            }
        }

        if (!ObjectUtils.isEmpty(admin)) {
            // 刷新token
            String newToken = JWTUtil.createJWT(admin.getPhone());
            System.out.println(newToken);
            response.setHeader(Constants.TOKEN,newToken);
            return true;
        } else {
            response.setStatus(Constants.STATUS_401);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(Result.error(Constants.STATUS_401,"未登录或登录已过期").toJson());
            return false;
        }
    }
}
